package cn.deali.homework9.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;

import cn.deali.homework9.model.Music;
import cn.deali.homework9.R;


public class PlaylistAdapter extends RecyclerView.Adapter {
    ArrayList<Music> musics;
    Context context;

    public PlaylistAdapter(Context context, ArrayList<Music> musics) {

        this.context = context;
        this.musics = musics;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.local_music_item, null);

        //返回ViewHolder实例
        return new PigViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Music music = musics.get(position);

        // holder是RecyclerView.ViewHolder类型，是父类，不能直接获取到子类PigViewHolder的组件imageView...
        final PigViewHolder pigViewHolder = (PigViewHolder) holder;

        if (music.getImgData() != null)
            pigViewHolder.imageView.setImageBitmap(music.getImgData());
        else
            Picasso.get().load(music.getImgUrl()).into(pigViewHolder.imageView);

        pigViewHolder.song_name.setText((String) music.getName());
        pigViewHolder.singer_name.setText((String) music.getArtist());
    }

    @Override
    public int getItemCount() {
        return musics.size();
    }

    class PigViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView song_name;
        TextView singer_name;


        public PigViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.img);
            song_name = itemView.findViewById(R.id.song_name);
            singer_name = itemView.findViewById(R.id.song_artist);

        }

    }
}
